Skip to main content
Glama
KnightMode

YouTube Search MCP Server

by KnightMode
youtube-search-api-usage.md10.6 kB
# YouTube Search API Usage Documentation ## Overview The YouTube Search API allows you to search for videos, channels, and playlists on YouTube. This API is part of the YouTube Data API v3 and provides comprehensive search functionality with various filtering options. ## Base URL ``` GET https://www.googleapis.com/youtube/v3/search ``` ## Authentication The API requires authentication via Google Cloud API key or OAuth 2.0 credentials. Some parameters require authorized requests. ## Quota Cost Each search request costs **100 units** from your daily quota limit. ## Required Parameters ### `part` (required) - **Value**: Must be set to `"snippet"` - **Description**: Specifies which resource properties to include in the response - **Example**: `part=snippet` ## Optional Parameters ### Search Query - **`q`**: Search query term - **Type**: String - **Example**: `q=cats` - **Description**: Search for videos containing the specified term ### Filtering Options - **`type`**: Resource type filter - **Values**: `video`, `channel`, `playlist` - **Example**: `type=video` - **Description**: Restricts results to specific resource types - **`channelId`**: Channel-specific search - **Type**: String - **Example**: `channelId=UC_x5XG1OV2P6uZZ5FSM9Ttw` - **Description**: Limits results to a specific channel - **`channelType`**: Channel type filter - **Values**: `any`, `show` - **Example**: `channelType=show` ### Result Customization - **`maxResults`**: Number of results per page - **Range**: 0-50 - **Default**: 5 - **Example**: `maxResults=25` - **`order`**: Result sorting method - **Values**: - `relevance` (default) - `date` - `rating` - `viewCount` - `title` - **Example**: `order=date` - **`pageToken`**: Pagination token - **Type**: String - **Example**: `pageToken=CAUQAA` - **Description**: Use `nextPageToken` from previous response ### Date Filtering - **`publishedAfter`**: Results published after this date - **Format**: RFC 3339 datetime - **Example**: `publishedAfter=2023-01-01T00:00:00Z` - **`publishedBefore`**: Results published before this date - **Format**: RFC 3339 datetime - **Example**: `publishedBefore=2023-12-31T23:59:59Z` ### Geographic Filtering - **`regionCode`**: Geographic region - **Format**: ISO 3166-1 alpha-2 country code - **Example**: `regionCode=US` - **`relevanceLanguage`**: Language for search results - **Format**: ISO 639-1 two-letter language code - **Example**: `relevanceLanguage=en` ### Video-Specific Filters - **`videoDuration`**: Video length filter - **Values**: `any`, `short`, `medium`, `long` - **Example**: `videoDuration=short` - **`videoDefinition`**: Video quality filter - **Values**: `any`, `high`, `standard` - **Example**: `videoDefinition=high` - **`videoLicense`**: License type filter - **Values**: `any`, `creativeCommon`, `youtube` - **Example**: `videoLicense=creativeCommon` ## Request Examples ### Basic Search ```http GET https://www.googleapis.com/youtube/v3/search?part=snippet&q=programming&key=YOUR_API_KEY ``` ### Advanced Search with Filters ```http GET https://www.googleapis.com/youtube/v3/search?part=snippet&q=javascript&type=video&order=date&maxResults=10&videoDuration=medium&key=YOUR_API_KEY ``` ### Channel-Specific Search ```http GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&order=date&maxResults=20&key=YOUR_API_KEY ``` ## Response Format ### Response Structure ```json { "kind": "youtube#searchListResponse", "etag": "etag_value", "nextPageToken": "token_for_next_page", "prevPageToken": "token_for_previous_page", "pageInfo": { "totalResults": 1000000, "resultsPerPage": 5 }, "items": [ { "kind": "youtube#searchResult", "etag": "item_etag", "id": { "kind": "youtube#video", "videoId": "video_id_here" }, "snippet": { "publishedAt": "2023-01-01T10:00:00Z", "channelId": "channel_id_here", "title": "Video Title", "description": "Video description...", "thumbnails": { "default": { "url": "https://i.ytimg.com/vi/video_id/default.jpg", "width": 120, "height": 90 }, "medium": { "url": "https://i.ytimg.com/vi/video_id/mqdefault.jpg", "width": 320, "height": 180 }, "high": { "url": "https://i.ytimg.com/vi/video_id/hqdefault.jpg", "width": 480, "height": 360 } }, "channelTitle": "Channel Name", "liveBroadcastContent": "none" } } ] } ``` ### Response Fields - **`kind`**: Resource type identifier - **`etag`**: Entity tag for caching - **`nextPageToken`**: Token for retrieving next page - **`prevPageToken`**: Token for retrieving previous page - **`pageInfo`**: Information about pagination - **`items`**: Array of search results ### Item Structure - **`id`**: Contains resource identifier (videoId, channelId, or playlistId) - **`snippet`**: Contains metadata about the resource - **`publishedAt`**: Publication date - **`channelId`**: Channel identifier - **`title`**: Resource title - **`description`**: Resource description - **`thumbnails`**: Available thumbnail images - **`channelTitle`**: Channel name - **`liveBroadcastContent`**: Live broadcast status ## Pagination ### Implementing Pagination ```javascript let nextPageToken = null; const allResults = []; do { const params = new URLSearchParams({ part: 'snippet', q: 'your search query', maxResults: '50', key: 'YOUR_API_KEY' }); if (nextPageToken) { params.append('pageToken', nextPageToken); } const response = await fetch(`https://www.googleapis.com/youtube/v3/search?${params}`); const data = await response.json(); allResults.push(...data.items); nextPageToken = data.nextPageToken; } while (nextPageToken && allResults.length < 500); ``` ## Rate Limits and Quotas ### Quota Information - **Default daily quota**: 10,000 units - **Search cost**: 100 units per request - **Maximum daily searches**: ~100 requests - **Rate limiting**: Apply reasonable delays between requests ### Best Practices 1. **Cache results** when possible to reduce API calls 2. **Use specific filters** to get relevant results 3. **Implement exponential backoff** for rate limit errors 4. **Monitor quota usage** regularly ## Error Handling ### Common Error Codes - **400 Bad Request**: Invalid parameters - **401 Unauthorized**: Invalid API key or insufficient permissions - **403 Forbidden**: Quota exceeded or access denied - **404 Not Found**: Resource not found - **500 Internal Server Error**: Server error ### Error Response Format ```json { "error": { "code": 400, "message": "Bad Request", "errors": [ { "domain": "youtube.parameter", "reason": "invalidValue", "message": "Invalid value for parameter part", "locationType": "parameter", "location": "part" } ] } } ``` ## Code Examples ### JavaScript/Node.js Example ```javascript const YOUTUBE_API_KEY = 'your_api_key_here'; const BASE_URL = 'https://www.googleapis.com/youtube/v3/search'; async function searchYouTube(query, options = {}) { const params = new URLSearchParams({ part: 'snippet', q: query, key: YOUTUBE_API_KEY, maxResults: options.maxResults || 25, type: options.type || 'video', order: options.order || 'relevance', ...options }); try { const response = await fetch(`${BASE_URL}?${params}`); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('YouTube API Error:', error); throw error; } } // Usage examples searchYouTube('machine learning', { maxResults: 10, order: 'date' }) .then(results => console.log(results)) .catch(error => console.error(error)); ``` ### Python Example ```python import requests from urllib.parse import urlencode class YouTubeSearchAPI: def __init__(self, api_key): self.api_key = api_key self.base_url = 'https://www.googleapis.com/youtube/v3/search' def search(self, query, **kwargs): params = { 'part': 'snippet', 'q': query, 'key': self.api_key, 'maxResults': kwargs.get('maxResults', 25), 'type': kwargs.get('type', 'video'), 'order': kwargs.get('order', 'relevance') } # Add additional parameters params.update(kwargs) try: response = requests.get(self.base_url, params=params) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"API Error: {e}") raise # Usage youtube = YouTubeSearchAPI('your_api_key_here') results = youtube.search('python programming', maxResults=10, order='date') ``` ## Important Limitations 1. **Search Result Limit**: Maximum 500 videos when using certain filters 2. **Pagination Limit**: Can only paginate through limited results 3. **Quota Restrictions**: Daily quota limits API usage 4. **Regional Restrictions**: Some content may not be available in all regions 5. **Real-time Updates**: Search results may have slight delays ## Security Considerations 1. **API Key Protection**: Never expose API keys in client-side code 2. **Environment Variables**: Store API keys in environment variables 3. **Rate Limiting**: Implement proper rate limiting to avoid abuse 4. **Input Validation**: Validate and sanitize search queries 5. **Error Handling**: Don't expose sensitive error information to users ## Troubleshooting ### Common Issues 1. **Invalid API Key**: Ensure API key is correctly configured in Google Cloud Console 2. **Quota Exceeded**: Monitor usage and implement caching 3. **Empty Results**: Check if search query and filters are too restrictive 4. **Pagination Issues**: Verify nextPageToken usage 5. **Parameter Errors**: Validate all parameter values before making requests ### Debugging Tips 1. Test API calls using tools like Postman or curl 2. Check Google Cloud Console for quota usage 3. Enable logging for API requests and responses 4. Use browser developer tools to inspect network requests 5. Validate JSON responses for proper structure

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/KnightMode/youtube-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server